<?php
require_once ROOT_PATH.'boot/req_inc.php';

class Log implements ILog,IRequestTool{
    const ERROR=1;
    const WARN=2;
    const INFO=3;
	const DEBUG=4;

	public $threshold	= self::ERROR;
	public $date_fmt	= 'Y-m-d H:i:s';
	public $is_split	=true;
	public $is_show_shop_log = true;
	public $level_hints=array(self::ERROR =>'req_log_error',self::WARN=>'req_log_warn',self::DEBUG=>'req_log_debug',self::INFO=>'req_log_info');
	//添加日志记录
	function error($msg){
		$this->write_log($msg);
	}
	function warn($msg){
		$this->write_log($msg,self::WARN);
	}
	function debug($msg){
		$this->write_log($msg,self::DEBUG);
	}
	function info($msg){
		$this->write_log($msg,self::INFO);
	}
	/**
	 * 创建日志
	 * @param $log_path 日志文件路径
	 */
	function __construct($log_path){
		$this->setLogPath($log_path);
	}

    public  $log_path;
    private $enabled	= false;
	function setLogPath($log_path)
	{
		$this->enabled=$log_path && is_dir($log_path) ;
		$this->log_path = $log_path;
	}

	/**
	 * Write Log File
	 * @param	string	the error level
	 * @param	string	the error message
	 */
	private function write_log($msg,$level = self::ERROR)
	{
		if ($this->enabled === false)	return ;
		if ($level > self::ERROR && $level > $this->threshold )	return ;
		$level= $level<self::ERROR ? self::ERROR :	$level>self::INFO ? self::INFO : $level;
		if(defined('RUN_DEBUGINFO_SEP') && RUN_DEBUGINFO_SEP ) $filepath = $this->log_path . 'debug_';
		else	$filepath = $this->log_path . 'error_';
		if($this->is_split)	$filepath .= date('Y-m-d');
		/**添加日志配置文件*/
		$web_name = $GLOBALS['context']->get_app_conf('web_name');
		if($this->is_show_shop_log) $filepath .='_'.$web_name;
		else $filepath .='_webadmin';
		$filepath .= '.log';
		$message = "[".date($this->date_fmt)."]\t[". lang($this->level_hints[$level])."]\t{$msg}\n";
		@file_put_contents($filepath,$message,FILE_APPEND);
	}
	static function register($prop) {
		$app_log_path=$GLOBALS['context']->get_app_conf('log_path');
		$app_log_split=$GLOBALS['context']->get_app_conf('log_split');
		$web_name = $GLOBALS['context']->get_app_conf('web_name');

		if (! $app_log_path){
			$app_log_path = ROOT_PATH . "logs" . DS;
			if(! file_exists($app_log_path)) mkdir($app_log_path);
		}
		if( !isset($app_log_split)) $app_log_split= true;

		$log = new Log ( $app_log_path );
		if (DEBUG)
			$log->threshold = Log::DEBUG;
		else
			$log->threshold = Log::ERROR;
		$log->is_split = $app_log_split;
		if( !isset($web_name)) $log->is_show_shop_log = false;
		//$log->debug ( 'Log object create' );
		return $log;
	}
}






